package Controller

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"hr-system/Global"
	"hr-system/Model"
	response "hr-system/Response"
	"strconv"
)

type IProbationEmployeeController interface {
	RestController
}

type ProbationEmployeeController struct {
	DB *gorm.DB
}

func NewProbationEmployeeController() IProbationEmployeeController{
	db := Global.GetDB()
	return ProbationEmployeeController{DB: db}
}

func (p ProbationEmployeeController) PageList(c *gin.Context) {
	name, _ := c.GetPostForm("name")
	if name != ""{
		var selectEmployee Model.ProbationEmployee

		// 查询
		result := p.DB.Model(&selectEmployee).Where("name=?", name).First(&selectEmployee).RowsAffected
		if result == 0 {
			response.Fail(c, "查无相关记录", nil)
			return
		}
		response.Success(c, gin.H{"data": selectEmployee}, "查询成功")
		return
	}
	// 获取分页参数
	tempNum, _ := c.GetQuery("pagenum")
	tempSize, _ := c.GetQuery("pagesize")
	pageNum, _ := strconv.Atoi(tempNum)   // 当前页数
	pageSize, _ := strconv.Atoi(tempSize) // 页内个数
	if pageNum == 0 || pageSize == 0 {
		pageNum = 1
		pageSize = 10
	}
	// 分页
	var record []Model.ProbationEmployee
	p.DB.Where("result=转正").Order("id").Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&record)

	// 前端渲染分页也要知道总数
	var total int64
	p.DB.Model(Model.ProbationEmployee{}).Count(&total)

	response.Success(c, gin.H{"data": record, "total": total}, "查询成功")
}

func (p ProbationEmployeeController) Create(c *gin.Context) {
	var requestEmployee Model.ProbationEmployee
	_ = c.ShouldBind(&requestEmployee)
	updateEmployee := Model.Employee{}
	result := p.DB.Where("id=?",requestEmployee.Id).First(&updateEmployee).RowsAffected
	if result == 0 {
		response.Fail(c, "该员工不存在", nil)
		return
	}
	if updateEmployee.IsQuit == "是" {
		response.Fail(c, "该员工已离职", nil)
		return
	}
	if updateEmployee.IsProbation == "否" {
		response.Fail(c, "该员工为正式员工", nil)
		return
	}
	err := p.DB.Create(&requestEmployee).Error
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	if requestEmployee.Result == "延期" {
		p.DB.Model(&updateEmployee).Update("probation_end",requestEmployee.DealDate)
		if err != nil {
			response.Fail(c, err.Error(), nil)
			return
		}
	}
	p.DB.Model(&updateEmployee).Update("is_probation","否")
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	response.Success(c, gin.H{"data": requestEmployee}, "操作成功")
}
